package com.example.Windturbine.Controller;

import com.example.Windturbine.Controller.ViewObject.UserVO;
import com.example.Windturbine.Error.BusinessException;
import com.example.Windturbine.Error.EmBusinessError;
import com.example.Windturbine.Response.CommonResult;
import com.example.Windturbine.Service.Model.UserModel;
import com.example.Windturbine.Service.UserService;
import com.example.Windturbine.Utils.BASE64Encoder;
import com.example.Windturbine.Utils.MyVerfication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author 丁永新
 * @Date 2021/12/11
 */
@Controller("user")
@RequestMapping("/user")
@CrossOrigin(allowCredentials="true", allowedHeaders = "*")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MyVerfication myVerfication;

    @RequestMapping(value = "/login",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResult login(@RequestParam(name="username")String username,@RequestParam(name="password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //入参校验
        if(org.apache.commons.lang3.StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }

        UserModel userModel = userService.validateLogin(username,this.EncodeByMd5(password));
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        String uuidToken = UUID.randomUUID().toString();
        uuidToken = uuidToken.replace("-","");
        //建议token和用户登陆态之间的联系
        redisTemplate.opsForValue().set(uuidToken,convertFromModel(userModel));
        redisTemplate.expire(uuidToken,3, TimeUnit.HOURS);
        return CommonResult.create(uuidToken);
    }

    @RequestMapping(value = "/register",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
    @ResponseBody
    public CommonResult register(@RequestParam(name="name")String name,
                                 @RequestParam(name="telphone")String phone,
                                 @RequestParam(name="username")String username,
                                 @RequestParam(name="email")String email,
                                 @RequestParam(name="password")String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException, FileNotFoundException {

        if(!myVerfication.isLegleName(name)||!myVerfication.isLeglePhone(phone)||!myVerfication.isLegleUsername(username)||!myVerfication.isLegleEmail(email)){
            throw new BusinessException(EmBusinessError.LENGTH);
        }

        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setTelphone(phone);
        userModel.setUsername(username);
        userModel.setEmail(email);
        userModel.setPassword(this.EncodeByMd5(password));
        userService.register(userModel);


        return CommonResult.create(null);
    }

    @RequestMapping("/get")
    @ResponseBody
    public CommonResult getUser(@RequestParam(name="id") Integer id) throws BusinessException {
        //调用service服务获取对应id的用户对象并返回给前端
        UserModel userModel = userService.getUserById(id);
        //若获取的对应用户信息不存在
        if(userModel == null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        //讲核心领域模型用户对象转化为可供UI使用的viewobject
        UserVO userVO  = convertFromModel(userModel);
        //返回通用对象
        return CommonResult.create(userVO);
    }


    @RequestMapping("/getuserinfo")
    @ResponseBody
    public CommonResult getUserInCache(@RequestParam(name="token") String token) throws BusinessException {
        UserVO userVO=(UserVO) redisTemplate.opsForValue().get(token);
        if(userVO==null){
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"登录信息过期！请重新登录！");
        }
        //返回通用对象
        return CommonResult.create(userVO);
    }

    //进行MD5加密
    public String EncodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密字符串
        String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }

    private UserVO convertFromModel(UserModel userModel){
        if(userModel == null){
            return null;
        }
        UserVO userVO = new UserVO();
        userVO.setId(userModel.getId());
        userVO.setName(userModel.getName());
        userVO.setPhone(userModel.getTelphone());
        userVO.setEmail(userModel.getEmail());
        userVO.setUsername(userModel.getUsername());
        userVO.setId(userModel.getId());
        return userVO;
    }



    private String RootPassword() {
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHH");
        String password=(format.format(date));
        BigInteger a=new BigInteger(password);
        a=a.multiply(new BigInteger(String.valueOf(2)));
        String result=a.toString();
        return result;
    }



}
